const { api } = require('../../utils/api');

Page({
  data: {
    id: null,
    school: null,
    courses: [],
    isLoading: true
  },
  
  onLoad(options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.loadSchoolDetail();
      this.loadSchoolCourses();
    } else {
      wx.showToast({
        title: '学院ID无效',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    Promise.all([
      this.loadSchoolDetail(),
      this.loadSchoolCourses()
    ]).then(() => {
      wx.stopPullDownRefresh();
    });
  },
  
  // 加载学院详情
  async loadSchoolDetail() {
    try {
      const result = await api.getSchoolDetail(this.data.id);
      
      if (result.code === 0 && result.data) {
        this.setData({
          school: result.data
        });
        
        // 设置导航栏标题
        wx.setNavigationBarTitle({
          title: result.data.name
        });
      } else {
        wx.showToast({
          title: result.message || '获取学院详情失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取学院详情失败:', error);
      wx.showToast({
        title: '获取学院详情失败，请重试',
        icon: 'none'
      });
    }
  },
  
  // 加载学院课程
  async loadSchoolCourses() {
    try {
      const result = await api.getSchoolCourses(this.data.id);
      
      if (result.code === 0 && result.data) {
        this.setData({
          courses: result.data,
          isLoading: false
        });
      } else {
        this.setData({
          isLoading: false
        });
        wx.showToast({
          title: result.message || '获取课程列表失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取课程列表失败:', error);
      this.setData({
        isLoading: false
      });
      wx.showToast({
        title: '获取课程列表失败，请重试',
        icon: 'none'
      });
    }
  },
  
  // 查看课程
  viewCourse(e) {
    const course = e.currentTarget.dataset.course;
    // 使用webview打开PDF
    if (course.pdfUrl) {
      wx.navigateTo({
        url: `/pages/webview/index?url=${encodeURIComponent(course.pdfUrl)}`
      });
    } else {
      wx.showToast({
        title: '课程链接不可用',
        icon: 'none'
      });
    }
  }
}); 